/*
 * -------------------------------------------------------------------------------------------------------*
 * SBS Priceboard V2.0
 * Copyright (C) 2008 Unicom Vietnam JSC
 * -------------------------------------------------------------------------------------------------------* 
 * HeadURL: http://192.168.1.4/svn/priceboard/trunk/SBS_PriceboardV2/front-end/end-user/enduser_priceboard/
 * LastChangeBy:
 * LastChangeDate:
 */
package com.unicom.priceboard.data.hose;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.log4j.Logger;
import com.unicom.priceboard.data.vo.PutAdElement;
import com.unicom.priceboard.thread.PutAdThread;
import com.unicom.priceboard.thread.SecurityThread;
import com.unicom.priceboard.util.MyComparator;
import com.unicom.priceboard.util.NumberUtil;
import com.unicom.priceboard.util.Util;

/**
 * Creation date: Jul 16, 2008
 * @author quan
 */
public class PutAdReader {
	
	private static final Logger logger = Logger.getLogger(PutAdReader.class);
	
	public void ParserAd(String path){
		try{
			FileInputStream instrPutAd = new FileInputStream(Util.getCurrentDataPath(path));
			parsePutAd(instrPutAd);
			instrPutAd.close();
		}catch(Exception e)	{
			logger.debug("not read file: "+e.getMessage());
		}
	}
	private void parsePutAd(InputStream is) {
		//List<PutAdElement> records = new ArrayList<PutAdElement>();
		DataInputStream input = new DataInputStream(is);
		try {
			while (input.available()>0) {
				PutAdElement record = new PutAdElement();

				// Create a new ByteBuffer to store a record from file
				ByteBuffer buf = ByteBuffer.allocate(27);
				// Set to little endian
				buf.order(ByteOrder.LITTLE_ENDIAN);
				// Get each field from the file and put it to the byte buffer
				buf.putShort(input.readShort()); // TradeId
				buf.putShort(input.readShort()); // SecurityNo
				buf.putInt(input.readInt()); // Volume
				buf.putDouble(input.readDouble()); // Price
				buf.putInt(input.readInt()); // FirmNo
				buf.put(input.readByte()); // Side
				buf.put(input.readByte()); // Board
				buf.putInt(input.readInt()); // Time
				buf.put(input.readByte()); // Flag

				// Reset position for reading
				buf.flip();
				// Set to big endian
				buf.order(ByteOrder.BIG_ENDIAN);

				// Retrieve data from byte buffer
				record.setTradeId(buf.getShort());
				record.setSecurityNo(buf.getShort());
				record.setVolume(NumberUtil.formatNumber(buf.getInt()));
				record.setPrice(NumberUtil.formatNumber(buf.getDouble()));
				record.setFirmNo(buf.getInt());
				record.setSide((char) buf.get());
				record.setBoard((char) buf.get());
				record.setTime(buf.getInt());
				record.setFlag((char) buf.get());
				
				String symbol;
				symbol=SecurityThread.lstSymbols.get(record.getSecurityNo());
				//System.out.println(symbol);
				record.setSymbol_code(symbol);
				//save to hash map with key identified by securityNo
				if(symbol!=null){
					String key=record.getTradeId()+"-"+record.getTime();
					 if(record.getFlag()!='C') {
						if(!PutAdThread.mapPutAd.containsKey(key)) {
							PutAdThread.mapPutAd.put(key,record);
						}else {
							PutAdElement objInList = PutAdThread.mapPutAd.get(key);
							if(!objInList.equals(record)) {
								PutAdThread.mapPutAd.put(key, record);
								//String itemName = "putAdElement_"+record.getTradeId();
							}
						}
					}else if(PutAdThread.mapPutAd.containsKey(key)) {
						PutAdThread.mapPutAd.remove(key);
					}//end if
				}
			}
			String strTempBuy = generateTradeIdList('B');
			String strTempSell = generateTradeIdList('S');
			strTempBuy=strTempBuy.trim();
			strTempSell=strTempSell.trim();
			if(strTempBuy.endsWith(","))
				strTempBuy=strTempBuy.substring(0,strTempBuy.length()-1);
			if(strTempSell.endsWith(","))
				strTempSell=strTempSell.substring(0,strTempSell.length()-1);
			//Update buy list to client if there's any change
			if(!PutAdThread.strBuy.equals(strTempBuy)) {							
				PutAdThread.strBuy=strTempBuy;//replace Buy String with new value
				
			}
			//Update buy list to client if there's any change
			if(!PutAdThread.strSell.equals(strTempSell)) {
				PutAdThread.strSell=strTempSell;//replace Sell String with new value
				
			}
		
		} catch (Exception ex) {
			
			}

	}
	
	public synchronized static String generateTradeIdList(Character BuySell) {
		StringBuffer retString = new StringBuffer("");
		List<String>  sortList = new ArrayList<String>();		
		sortList.addAll(PutAdThread.mapPutAd.keySet());		
		Collections.sort(sortList,new MyComparator());
		for(int i=0;i<sortList.size();i++) {			
			PutAdElement putAdobj = PutAdThread.mapPutAd.get(sortList.get(i));
			if(i<sortList.size()-1) {
				if(putAdobj.getSide()==BuySell){
					retString.append(sortList.get(i)+",");
				}
			}else {
				if(putAdobj.getSide()==BuySell)
					retString.append(sortList.get(i));
			}
			
		}
		return retString.toString();
	}
}
